﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StoragePeriod.Common;
using StoragePeriod.Data;
using StoragePeriod.Web.Common;
using System.Text;
using StoragePeriod.Model.StorageForecast;
using StoragePeriod.BLL.StorageForecast;
using System.Data;
using StoragePeriod.BLL.RawDict;
using StoragePeriod.Model.RawDict;

namespace StoragePeriod.Web.StorageForecast.WhereSelect
{
    public partial class WhereSelectList : SecurityPage
    {
        T_RawMaterial tRawMaterial = new T_RawMaterial();   //原料操作
        T_RawNorm tRawNorm = new T_RawNorm(); //极限值
        T_StorageCalculateMove tStorageCalculateMove = new T_StorageCalculateMove(); //计算公式
        T_StorageCalculateResult tStorageCalculateResult = new T_StorageCalculateResult();//贮存期预测结果
        T_IntroduceStorage tIntroduceStorage = new T_IntroduceStorage();//贮存知识
        T_QualityCalculateLog tQualityCalculateLog = new T_QualityCalculateLog();//计算日志操作
        T_QualityResult tQualityResult = new T_QualityResult();//保存的计算结果操作
        T_RawMaterialType tRawMaterialType = new T_RawMaterialType();//原料类别操作

        //绑定下拉菜单
        private void DropBandingSearch()
        {
            List<OperationTeam> OperationList = OperationTeam.Where("ParentId=@0", 0).OrderByDescending(p => p.id).ToList();
            this.Drop_OperationSearch.DataSource = OperationList;
            this.Drop_OperationSearch.DataValueField = "id";
            this.Drop_OperationSearch.DataTextField = "OTName";
            this.Drop_OperationSearch.DataBind();
            this.Drop_OperationSearch_SelectedIndexChanged(null, null);

            List<RawMaterialType> TargetsList = RawMaterialType.Where("ParentId=@0 and TypeInfoid=@1", 0, Convert.ToInt32(EnumData.TypeInfo.预测指标)).OrderByDescending(p => p.id).ToList();
            this.Drop_Targets.DataSource = TargetsList;
            this.Drop_Targets.DataValueField = "id";
            this.Drop_Targets.DataTextField = "TypeName";
            this.Drop_Targets.DataBind();
            this.Drop_Targets_SelectedIndexChanged(null, null);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            BindTreeView();
            DropBandingSearch();
            LeftLable.Text = "贮存条件选择";

            SYS_Users md = SYS_Users.Where("UserCode=@0", User.Identity.Name).First();
            OperationTeam team = OperationTeam.Where("id=@0", Convert.ToInt32(md.UserType)).First();
            this.Drop_OperationSearch.SelectedValue = team.ParentId.ToString();
            this.Drop_OperationSearch_SelectedIndexChanged(null, null);
            this.Drop_TeamSearch.SelectedValue = team.id.ToString();
            if (md.RoleName != "管理员")
            {
                this.Drop_OperationSearch.Enabled = false;
                this.Drop_TeamSearch.Enabled = false;
            }
        }

        //绑定原料树
        public void BindTreeView()
        {
            NutrientsTree.Nodes.Clear();
            List<RawMaterialType> RawTypeList = RawMaterialType.Where("ParentId=@0 and Typeinfoid=@1", 0, Convert.ToInt32(EnumData.TypeInfo.食品检测)).ToList();
            RawTypeList.ForEach(p =>
            {
                TreeNode childNode = new TreeNode()
                {
                    Text = p.TypeName,
                    Value = p.id.EToString(),
                    Target = "Parent",
                };
                childNode = GetRawByTypeId(childNode);
                NutrientsTree.Nodes.Add(childNode);
            });
            SysTree_SelectedNodeChanged(null, null);
        }
        private TreeNode GetRawByTypeId(TreeNode tn)
        {
            int Pid = int.Parse(tn.Value);
            List<RawMaterialType> RawTypeList = RawMaterialType.Where("ParentId=@0", Pid).ToList();
            RawTypeList.ForEach(p =>
            {
                TreeNode childNode = new TreeNode()
                {
                    Text = p.TypeName,
                    Value = p.id.ToString(),
                    Target = "Parent"
                };
                childNode = GetRawByTypeId(childNode);
                tn.ChildNodes.Add(childNode);
            });

            int TypeId = int.Parse(tn.Value);
            List<E_RawMaterial> rmlist = tRawMaterial.GetModelList("PeriodTypeStorageID ="+TypeId);

            rmlist.ForEach(a =>
            {
                TreeNode rnod = new TreeNode()
                {
                    Text = a.RAWName,
                    Value = a.id.EToString(),
                    Target = "Child"
                };
                tn.ChildNodes.Add(rnod);
            });
            return tn;
        }

        protected void SysTree_SelectedNodeChanged(object sender, EventArgs e)
        {
            TreeNode tn = this.NutrientsTree.SelectedNode;
            if (tn != null && tn.Target == "Child")
            {
                int RawID = int.Parse(tn.Value);

                this.lbl_SelRawName.Text = "";//已选原料
                this.lbl_SelRawName.Text = "已选原料：" + tn.Text;//原料名称
                this.HidRawID.Value = tn.Value;//原料ID
                this.txt_Temperature.Text = "";
                this.txt_licunTime.Text = "";

                E_IntroduceStorage eIntroduceStorage = tIntroduceStorage.GetModelList("RawID=" + RawID).FirstOrDefault();
                if (eIntroduceStorage != null)
                {
                    this.lab_StoragePrompt.Text = eIntroduceStorage.StoragePrompt.ToString();
                }
                else
                {
                    this.lab_StoragePrompt.Text = ""; 
                }

                //加载对应指标
                this.Drop_Targets_SelectedIndexChanged(null, null);
                //加载推荐极值
                this.Drop_TargetsInfo_SelectedIndexChanged(null, null);
            }
        }

        //删除 贮存知识
        protected void btn_Del_Click(object sender, EventArgs e)
        {
        }

        //查询原料树
        protected void btn_search_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Txt_Search.Text))
            {
                return;
            }
            for (int i = 0; i < NutrientsTree.Nodes.Count; i++)
            {
                for (int ii = 0; ii < NutrientsTree.Nodes[i].ChildNodes.Count; ii++)
                {
                    if (NutrientsTree.Nodes[i].ChildNodes[ii].Text.Contains(Txt_Search.Text))
                    {
                        TreeNode node = NutrientsTree.Nodes[i].ChildNodes[ii];
                        string text = node.Text;
                        node.Text = HttpUtility.HtmlDecode(node.Text).Replace(Txt_Search.Text, "<span class='Red'>" + Txt_Search.Text + "</span>");
                    }
                }
            }
        }

        //加载班组
        protected void Drop_OperationSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.Drop_OperationSearch.SelectedItem != null)
            {
                int ParentId = Convert.ToInt32(this.Drop_OperationSearch.SelectedValue);
                List<OperationTeam> TeamList;
                if (ParentId == -1)
                {
                    TeamList = new List<OperationTeam>();
                }
                else
                {
                    TeamList = OperationTeam.Where("ParentId=@0", ParentId).ToList();
                }
                this.Drop_TeamSearch.DataSource = TeamList;
                this.Drop_TeamSearch.DataValueField = "id";
                this.Drop_TeamSearch.DataTextField = "OTName";
                this.Drop_TeamSearch.DataBind();
            }
        }

        //加载二级指标
        protected void Drop_Targets_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.Drop_Targets.SelectedItem != null && this.HidRawID.Value != "")
            {
                int RawID = int.Parse(this.HidRawID.Value);
                E_RawMaterial eRawMaterial = tRawMaterial.GetModel(RawID);
                int RawTypeID = int.Parse(eRawMaterial.PeriodTypeStorageID.ToString());
                E_RawMaterialType eRawMaterialType = tRawMaterialType.GetModel(RawTypeID);
                if (eRawMaterialType.ParentId > 0)
                {
                    this.GetRawParentTtypeID(ref RawTypeID);
                }
                int ParentId = Convert.ToInt32(this.Drop_Targets.SelectedValue);
                List<E_RawMaterialType> list = tRawMaterialType.GetModelList("ParentId=" + ParentId + " and RawTypePath like '%|" + RawTypeID + "%|'").ToList();

                this.Drop_TargetsInfo.DataSource = list;
                this.Drop_TargetsInfo.DataValueField = "id";
                this.Drop_TargetsInfo.DataTextField = "TypeName";
                this.Drop_TargetsInfo.DataBind();

                this.Drop_TargetsInfo_SelectedIndexChanged(null, null);
            }
        }

        //获取根类别ID
        private void GetRawParentTtypeID(ref int RawTypeID)
        {
            E_RawMaterialType eRawMaterialType = tRawMaterialType.GetModel(RawTypeID);
            RawTypeID = int.Parse(eRawMaterialType.ParentId.ToString());
            E_RawMaterialType Temp = tRawMaterialType.GetModel(RawTypeID);
            if (Temp.ParentId > 0)
            {
                this.GetRawParentTtypeID(ref RawTypeID);
            }
        }

        //加载极限值
        protected void Drop_TargetsInfo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.HidRawID.Value != "" && this.Drop_TargetsInfo.SelectedItem != null)
            {
                int RawID = Convert.ToInt32(this.HidRawID.Value); //原料ID
                int QuotaID = Convert.ToInt32(this.Drop_TargetsInfo.SelectedValue); //指标ID

                List<E_RawNorm> list = tRawNorm.GetModelList("RawId=" + RawID + " and NormId=" + QuotaID);
                if (list.Count > 0)
                {
                    this.Drop_Norm.DataSource = list;
                    this.Drop_Norm.DataValueField = "id";
                    this.Drop_Norm.DataTextField = "ElectValue";
                    this.Drop_Norm.DataBind();
                    this.Drop_Norm.SelectedIndex = 0;
                }
                else
                {
                    this.Drop_Norm.Items.Clear();
                }
            }
        }

        //贮存期预测
        protected void Btn_Calulate_Click(object sender, EventArgs e)
        {
            int RawID = Convert.ToInt32(this.HidRawID.Value);   //原料ID
            decimal licunTime=decimal.Parse(this.txt_licunTime.Text.Trim()); //库存时间
            if (this.Drop_Norm.SelectedItem == null)
            {
                UtilityUI.Alert(this.UpdatePanel1, "请选择推荐极值！");
                return;
            }
            int NormID = int.Parse(this.Drop_Norm.SelectedValue);//极限值


            E_StorageCalculateMove md = tStorageCalculateMove.GetModelList("RawID=" + RawID + " and NormID=" + NormID).FirstOrDefault();
            if (md == null)
            {
                UtilityUI.Alert(this.UpdatePanel1, "没有对应极限值下的贮存期预测模型！");
                return;
            }

            //t（时间）=M*10负次方N*e正次方Z/T 其中:e=2.71828  t:贮存时间(d);  T：贮存温度（K）,其中K=℃+273
            //A的N次方=B 求N
            //decimal t = Convert.ToDecimal(md.M) * Convert.ToDecimal(Math.Pow(10, Convert.ToDouble(-1 * md.N)) * Math.Pow(2.71828, Convert.ToDouble(md.Z / (Temperature + 273))));//时间
            decimal Th=Convert.ToDecimal(Math.Log(Convert.ToDouble(licunTime/(Convert.ToDecimal(md.M) * Convert.ToDecimal(Math.Pow(10, Convert.ToDouble(-1 * md.N))))),2.71828)); //得到次方数
            decimal T = Convert.ToDecimal(md.Z) / Th; //得到温度（K）
            this.txt_Temperature.Text = (T - 273).ToString("f2"); //获取温度（℃）


            //添加计算日志
            E_QualityCalculateLog eQualityCalculateLog = new E_QualityCalculateLog();
            eQualityCalculateLog.RawID = RawID;
            eQualityCalculateLog.RawName = this.NutrientsTree.SelectedNode.Text;
            eQualityCalculateLog.QuotaID = int.Parse(this.Drop_TargetsInfo.SelectedValue);
            eQualityCalculateLog.QuotaName = this.Drop_TargetsInfo.SelectedItem.Text;
            eQualityCalculateLog.NormID = int.Parse(this.Drop_Norm.SelectedValue);//极限值ID
            eQualityCalculateLog.ElectValue = this.Drop_Norm.SelectedItem.Text;//极限值
            eQualityCalculateLog.CalculateResult = "贮存期为：" + licunTime + "(天)时，库存温度应为：" + this.txt_Temperature.Text + "(℃)；   ";
            eQualityCalculateLog.AddTime = DateTime.Now;
            eQualityCalculateLog.CalculateTypeID = 3;//估算类型ID（1：品质估算、2：贮存期预测、3：贮存条件选择）
            eQualityCalculateLog.OAreaID = int.Parse(this.Drop_OperationSearch.SelectedValue); //作业区ID
            eQualityCalculateLog.TeamID = int.Parse(this.Drop_TeamSearch.SelectedValue); //班组ID
            tQualityCalculateLog.Add(eQualityCalculateLog);
        }

        //保存评估结果
        protected void Btn_SaveCalulate_Click(object sender, EventArgs e)
        {
            int RawID = Convert.ToInt32(this.HidRawID.Value);   //原料ID
            int NormID = int.Parse(this.Drop_Norm.SelectedValue);//极限值
            decimal licunTime = decimal.Parse(this.txt_licunTime.Text.Trim()); //库存时间

            E_StorageCalculateResult eStorageCalculateResult = new E_StorageCalculateResult();
            eStorageCalculateResult.RawID = RawID;
            eStorageCalculateResult.NormID = NormID;
            eStorageCalculateResult.Temperature = Convert.ToDecimal(this.txt_Temperature.Text.Trim());
            eStorageCalculateResult.LicunTime = Convert.ToDecimal(this.txt_licunTime.Text.Trim());
            eStorageCalculateResult.AddTime = DateTime.Now;
            tStorageCalculateResult.Add(eStorageCalculateResult);

            int QuotaID = int.Parse(this.Drop_TargetsInfo.SelectedValue);//指标ID
            E_QualityResult eQualityResult = new E_QualityResult();
            eQualityResult.RawID = RawID;
            eQualityResult.RawName = this.NutrientsTree.SelectedNode.Text;
            eQualityResult.QuotaID = QuotaID;
            eQualityResult.QuotaName = this.Drop_TargetsInfo.SelectedItem.Text;
            eQualityResult.NormID = int.Parse(this.Drop_Norm.SelectedValue);//极限值ID
            eQualityResult.ElectValue = this.Drop_Norm.SelectedItem.Text;//极限值
            eQualityResult.CalculateResult = "贮存期为：" + licunTime + "(天)时，库存温度应为：" + this.txt_Temperature.Text + "(℃)；   ";
            eQualityResult.AddTime = DateTime.Now;
            eQualityResult.CalculateTypeID = 3;//估算类型ID（1：品质估算、2：贮存期预测、3：贮存条件选择）
            eQualityResult.OAreaID = int.Parse(this.Drop_OperationSearch.SelectedValue); //作业区ID
            eQualityResult.TeamID = int.Parse(this.Drop_TeamSearch.SelectedValue); //班组ID
            tQualityResult.Add(eQualityResult);
            UtilityUI.Alert(this.UpdatePanel1, "保存成功！");
        }
    }
}